<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>MathBox - 3D Grapher</title>
  <script src="mathbox-bundle.js"></script>
  <script src="dat.gui.js"></script>
  
<!-- http://silentmatt.com/javascript-expression-evaluator/ -->
<script src="parser.js"></script>

  <link rel="stylesheet" href="mathbox.css">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1">
</head>
<body>
  <script>
    var mathbox = mathBox({
      plugins: ['core', 'controls', 'cursor', 'mathbox'],
      controls: {klass: THREE.OrbitControls}
    });
    if (mathbox.fallback) throw "WebGL not supported"

    var three = mathbox.three;
    three.renderer.setClearColor(new THREE.Color(0xFFFFFF), 1.0);

	var graphData, view;
	
	var functionText = "sin(a*x + b*x*y)";
	
	var pointText = "(1,1)";
	
	var a = 1, b = 1;
	var	xMin = -3, xMax = 3, yMin = -3,	yMax = 3, zMin = -3, zMax = 3;
	
	var zAutofit = true;
	
	// start of updateGraph function ==============================================================
	var updateGraphFunc = function() 
	{ 
		var zFunc = Parser.parse( functionText ).toJSFunction( ['x','y'] );
		graphData.set("expr", 
		    function (emit, x, y, i, j, t) 
			{ 
			    emit( x, zFunc(x,y), y );
			}
		);
		
		if (zAutofit)
		{
			var xStep = (xMax - xMin) / 256;
			var yStep = (yMax - yMin) / 256;
			var zSmallest = zFunc(xMin, yMin);
			var zBiggest  = zFunc(xMin, yMin);
			for (var x = xMin; x <= xMax; x += xStep)
			{
				for (var y = yMin; y <= yMax; y += yStep)
				{
					var z = zFunc(x,y);
					if (z < zSmallest) zSmallest = z;
					if (z > zBiggest)  zBiggest  = z;
				}
			}
			zMin = zSmallest;
			zMax = zBiggest;
		}
		view.set("range", [[xMin, xMax], [zMin,zMax], [yMin, yMax]]); 

		if (graphColorStyle == "Grayscale")
		{
			// zMax = white, zMin = black
			graphColors.set("expr", 
				function (emit, x, y, i, j, t) 
				{ 
					var z = zFunc(x,y);
					var percent = (z - zMin) / (zMax - zMin);
					emit( percent, percent, percent, 1.0 );
				}
			);
		}
		else if (graphColorStyle == "Rainbow")
		{
			// rainbow hue; zMax = red, zMin = violet			
			graphColors.set("expr", 
				function (emit, x, y, i, j, t) 
				{ 
					var z = zFunc(x,y);
					var percent = (z - 1.2 * zMin) / (zMax - 1.2 * zMin);
					var color = new THREE.Color( 0xffffff );
					color.setHSL( 1-percent, 1, 0.5 );
					emit( color.r, color.g, color.b, 1.0 );
				}
			);
		}
		else if (graphColorStyle == "Solid Blue")
		{
			// just a solid blue color			
			graphColors.set("expr", 
				function (emit, x, y, i, j, t) 
				{ 
					emit( 0.5, 0.5, 1.0, 1.0 );
				}
			);
		}
	
	} 
	// end of updateGraph function ==============================================================
	
	
	var updateGraph = function() { updateGraphFunc(); };

	
	// setting proxy:true allows interactive controls to override base position
	var camera = mathbox.camera( { proxy: true, position: [4,2,4] } );

	 // save as variable to adjust later
    view = mathbox.cartesian(
	  {
        range: [[xMin, xMax], [yMin, yMax], [zMin,zMax]],
        scale: [2,1,2],
      }
	);

	// axes
	var xAxis = view.axis( {axis: 1, width: 8, detail: 40, color:"red"} );
    var xScale = view.scale( {axis: 1, divide: 10, nice:true, zero:true} );
    var xTicks = view.ticks( {width: 5, size: 15, color: "red", zBias:2} );
    var xFormat = view.format( {digits: 2, font:"Arial", weight: "bold", style: "normal", source: xScale} );
    var xTicksLabel = view.label( {color: "red", zIndex: 0, offset:[0,-20], points: xScale, text: xFormat} );
	
	var yAxis = view.axis( {axis: 3, width: 8, detail: 40, color:"green"} );
    var yScale = view.scale( {axis: 3, divide: 5, nice:true, zero:false} );
    var yTicks = view.ticks( {width: 5, size: 15, color: "green", zBias:2} );
    var yFormat = view.format( {digits: 2, font:"Arial", weight: "bold", style: "normal", source: yScale} );
    var yTicksLabel = view.label( {color: "green", zIndex: 0, offset:[0,0], points: yScale, text: yFormat} );
	
	var zAxis = view.axis( {axis: 2, width: 8, detail: 40, color:"blue"} );
    var zScale = view.scale( {axis: 2, divide: 5, nice:true, zero:false} );
    var zTicks = view.ticks( {width: 5, size: 15, color: "blue", zBias:2} );
    var zFormat = view.format( {digits: 2, font:"Arial", weight: "bold", style: "normal", source: zScale} );
    var zTicksLabel = view.label( {color: "blue", zIndex: 0, offset:[0,0], points: zScale, text: zFormat} );
	
	view.grid( {axes:[1,3], width: 2, divideX: 20, divideY: 20, opacity:0.25} );
	
	var graphData = view.area({
		axes: [1,3], channels: 3, width: 64, height: 64,
        expr: function (emit, x, y, i, j, t)
		{
		  var z = x*y;
          emit( x, z, y );
        },
    });
	
	// actuall emitter set later.
	var graphColors = view.area({
		expr: function (emit, x,y, i,j, t) 
		{
			if (x < 0)
				emit(1.0, 0.0, 0.0, 1.0);
		    else
				emit(0.0, 1.0, 0.0, 1.0);
		},
		axes: [1,3],
		width:  64, height: 64,
		channels: 4, // RGBA
    });
	
	// create graph in two parts, because want solid and wireframe to be different colors
	// shaded:false for a solid color (curve appearance provided by mesh)
	// width: width of line mesh
	// note: colors will mult. against color value, so set color to white (#FFFFFF) to let colors have complete control.
	var graphShaded = false;	
	var graphViewSolid = view.surface({
		points:graphData, 
		color:"#FFFFFF", shaded:false, fill:true, lineX:false, lineY:false, colors:graphColors, visible:true, width:0
	});
	
	var graphWireVisible = true;
	var graphViewWire = view.surface({
		points: graphData,
		color:"#000000", shaded:false, fill:false, lineX:true, lineY:true, visible:graphWireVisible, width:2
    });
	
    // GUI controls
	
	var gui = new dat.GUI();
	
	gui.add( this, 'functionText' ).name('y = f(x) = ');
	
	var graphColorStyle = "Rainbow";
	var graphColorStyleList = ["Solid Blue", "Grayscale", "Rainbow"];
	var graphColorGUI = gui.add( this, "graphColorStyle", graphColorStyleList ).name('Graph style').onChange( updateGraphFunc );


	var graphWireVisibleGUI = gui.add( this, "graphWireVisible" ).name("View wireframe").onChange(
		function()
		{
			graphViewWire.set("visible", graphWireVisible);
		}
	);
	var graphShadedGUI = gui.add( this, "graphShaded" ).name("View shading").onChange(
		function()
		{
			graphViewSolid.set("shaded", graphShaded);
		}
	);
	
	var folder0 = gui.addFolder('Parameters');
	var aGUI = folder0.add( this, 'a' ).min(0).max(5).step(0.01).name('a = ');
	var bGUI = folder0.add( this, 'b' ).min(0).max(5).step(0.01).name('b = ');
	folder0.close();
	
	var folder1 = gui.addFolder('Window Range');
	var xMinGUI = folder1.add( this, 'xMin' );
	var xMaxGUI = folder1.add( this, 'xMax' );
	var zMinGUI = folder1.add( this, 'zMin' ).name("yMin");
	var zMaxGUI = folder1.add( this, 'zMax' ).name("yMax");
	folder1.close();
	
	gui.add( this, 'updateGraph' ).name("Update Graph");
	
	// onChange or onFinishChange
	aGUI.onChange( updateGraphFunc );
	bGUI.onChange( updateGraphFunc );
	
	gui.open();
	
	updateGraphFunc();
	</script>
</body>
</html>
